package com.zhs.xyzsdk.editors;

import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.TextAttribute;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.ITokenScanner;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.swt.SWT;

import com.zhs.javacc.XYZParserConstants;
import com.zhs.xyzsdk.editors.token.CommonToken;
import com.zhs.xyzsdk.editors.token.TokenList;
import com.zhs.xyzsdk.editors.token.TokenManager;

public class ExprTokenScanner implements ITokenScanner {
	/*
	 * JFace token type definition
	 */

	private static IToken KEYWORD = new Token(
			new TextAttribute(ColorManager.getInstance().getColor(
					IXYZColorConstants.KEYWORD), null, SWT.BOLD));
	private static IToken ID = new Token(new TextAttribute(ColorManager
			.getInstance().getColor(IXYZColorConstants.ID)));
	private static IToken DEFAULT = new Token(new TextAttribute(ColorManager
			.getInstance().getColor(IXYZColorConstants.DEFAULT)));
	private static IToken OTHER = new Token(new TextAttribute(ColorManager
			.getInstance().getColor(IXYZColorConstants.COMMENT)));

	// character offset
	private int offset;

	// last token returned by nextToken()
	private CommonToken lastToken;

	private TokenList tokenList;

	public ExprTokenScanner() {
		offset = 0;
	}

	public int getTokenLength() {
		int l = lastToken.getStopIndex() - lastToken.getStartIndex() + 1;
		return l;
	}

	public int getTokenOffset() {
		return lastToken.getStartIndex();

	}

	public IToken nextToken() {
		if (lastToken == null)
			lastToken = tokenList.getToken(offset);
		else
			lastToken = tokenList.getNextToken(lastToken);

		if (lastToken == null)
			return Token.UNDEFINED;
		// if (lastToken.getToken().kind==XYZParserConstants.EOF){
		// lastToken.setStartIndex(0);
		// lastToken.setStopIndex(0);
		// }
		if (lastToken.getToken().kind >= XYZParserConstants.BOOLEAN
				&& lastToken.getToken().kind <= XYZParserConstants.VOID)
			return KEYWORD;

		switch (lastToken.getToken().kind) {
		case XYZParserConstants.IDENTIFIER:
			return ID;
		case TokenManager.OTHER:
			return OTHER;
		case XYZParserConstants.EOF:
			return Token.EOF;
		default:
			return DEFAULT;
		}
	}

	public void setRange(IDocument document, int offset, int length) {
		System.out.println("set Range:" + " " + offset + " " + length);
		lastToken = null;
		this.offset = offset;
		tokenList = TokenManager.getTokenList(document);
	}
}
